package com.gameplatform.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gameplatform.model.Game;
import com.gameplatform.service.GameService;
import com.gameplatform.util.ResponseUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class GameServlet extends HttpServlet {
    private GameService gameService = new GameService();
    private ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        String category = request.getParameter("category");
        
        if (pathInfo == null || pathInfo.equals("/")) {
            // 获取所有游戏或按分类筛选
            List<Game> games;
            if (category != null && !category.trim().isEmpty()) {
                games = gameService.getGamesByCategory(category);
            } else {
                games = gameService.getAllGames();
            }
            ResponseUtil.writeResponse(response, 200, "success", games);
        } else if (pathInfo.startsWith("/")) {
            String[] parts = pathInfo.split("/");
            if (parts.length == 2) {
                try {
                    int gameId = Integer.parseInt(parts[1]);
                    Game game = gameService.getGameById(gameId);
                    if (game != null) {
                        ResponseUtil.writeResponse(response, 200, "success", game);
                    } else {
                        ResponseUtil.writeResponse(response, 404, "Game not found", null);
                    }
                } catch (NumberFormatException e) {
                    ResponseUtil.writeResponse(response, 400, "Invalid game ID", null);
                }
            }
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        
        if (pathInfo != null && pathInfo.equals("/like")) {
            // 点赞游戏
            Map<String, Object> requestData = objectMapper.readValue(request.getInputStream(), Map.class);
            Object gameIdObj = requestData.get("gameId");
            
            try {
                int gameId;
                if (gameIdObj instanceof Integer) {
                    gameId = (Integer) gameIdObj;
                } else {
                    gameId = Integer.parseInt(gameIdObj.toString());
                }
                
                boolean success = gameService.likeGame(gameId);
                if (success) {
                    ResponseUtil.writeResponse(response, 200, "Game liked successfully", null);
                } else {
                    ResponseUtil.writeResponse(response, 500, "Failed to like game", null);
                }
            } catch (Exception e) {
                ResponseUtil.writeResponse(response, 400, "Invalid game ID", null);
            }
        } else if (pathInfo != null && pathInfo.equals("/favorite")) {
            // 收藏游戏
            Map<String, Object> requestData = objectMapper.readValue(request.getInputStream(), Map.class);
            Object gameIdObj = requestData.get("gameId");
            
            try {
                int gameId;
                if (gameIdObj instanceof Integer) {
                    gameId = (Integer) gameIdObj;
                } else {
                    gameId = Integer.parseInt(gameIdObj.toString());
                }
                
                boolean success = gameService.favoriteGame(gameId);
                if (success) {
                    ResponseUtil.writeResponse(response, 200, "Game favorited successfully", null);
                } else {
                    ResponseUtil.writeResponse(response, 500, "Failed to favorite game", null);
                }
            } catch (Exception e) {
                ResponseUtil.writeResponse(response, 400, "Invalid game ID", null);
            }
        } else {
            // 创建新游戏
            Game game = objectMapper.readValue(request.getInputStream(), Game.class);
            boolean success = gameService.createGame(game);
            
            if (success) {
                ResponseUtil.writeResponse(response, 201, "Game created successfully", game);
            } else {
                ResponseUtil.writeResponse(response, 500, "Failed to create game", null);
            }
        }
    }
    
    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        
        if (pathInfo != null && pathInfo.startsWith("/")) {
            String[] parts = pathInfo.split("/");
            if (parts.length == 2) {
                try {
                    int gameId = Integer.parseInt(parts[1]);
                    Game game = objectMapper.readValue(request.getInputStream(), Game.class);
                    game.setId(gameId);
                    
                    boolean success = gameService.updateGame(game);
                    if (success) {
                        ResponseUtil.writeResponse(response, 200, "Game updated successfully", game);
                    } else {
                        ResponseUtil.writeResponse(response, 500, "Failed to update game", null);
                    }
                } catch (NumberFormatException e) {
                    ResponseUtil.writeResponse(response, 400, "Invalid game ID", null);
                }
            }
        }
    }
    
    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        
        if (pathInfo != null && pathInfo.startsWith("/")) {
            String[] parts = pathInfo.split("/");
            if (parts.length == 2) {
                try {
                    int gameId = Integer.parseInt(parts[1]);
                    boolean success = gameService.deleteGame(gameId);
                    
                    if (success) {
                        ResponseUtil.writeResponse(response, 200, "Game deleted successfully", null);
                    } else {
                        ResponseUtil.writeResponse(response, 500, "Failed to delete game", null);
                    }
                } catch (NumberFormatException e) {
                    ResponseUtil.writeResponse(response, 400, "Invalid game ID", null);
                }
            }
        }
    }
}